<template>
  <!-- 登录界面 -->
  <div class="cont" v-if="status === 1">
    <div class="tent">
      <div class="tleft">
        <img class="ti" src="../assets/biao.png" alt="">
      </div>
      <div class="tright">
        <div class="a1">智能配送</div>
        <div class="a2">一款智能AI平台</div>
        <div class="a3">
          <div>
            <img class="icon1" src="../assets/user.png" alt="">
          </div>
          <div class="a31">
            <input class="input1" type="text" v-model="emailInputValue" placeholder="请输入邮箱">
          </div>
        </div>
        <div class="a4">
          <div>
            <img class="icon2" src="../assets/lock.png" alt="">
          </div>
          <div class="a41">
            <input class="input2" :type="passwordType" placeholder="请输入登录密码" v-model="password">
          </div>
          <div class="a42" @click="togglePassword">
          </div>
        </div>
        <div class="a5">
          <div class="a50">
            <el-checkbox
              v-model="checked"
              checked-color="#3895c5"
              unchecked-color="#dcdcdc"
            ></el-checkbox>
            <div class="a51">记住密码</div>
          </div>
          <div class="a52"></div>
          <a href="#" class="a53" @click="pass">忘记密码？</a>
        </div>
        <div class="a6">
          <div class="a61" @click="login">登录</div>
          <div class="a62" @click="goToRegister">注册</div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 注册界面 -->
  <div class="cont" v-if="status === 2">
    <div class="tent">
      <div class="tleft">
        <img class="ti" src="../assets/biao.png" alt="">
      </div>
      <div class="tright">
        <div class="a11">智能配送</div>
        <div class="a22">一款智能AI平台</div>
        <div class="a3a">
          <div>
            <img class="icon11" src="../assets/email.png" alt="">
          </div>
          <div class="a31">
            <input class="input11" type="text" placeholder="请输入邮箱" v-model="emailInputValue">
          </div>
        </div>
        <div class="a3a">
          <div>
            <img class="icon11" src="../assets/verify.png" alt="">
          </div>
          <div class="a31">
            <input class="input1" type="text" v-model="verificationCode" placeholder="请输入验证码">
            <div class="a311">
              <el-button @click="checkEmailAndSendCode" class="btn" type="primary" :disabled="isCounting || isEmailRegistered" plain>{{ maxTime }}</el-button>
            </div>
          </div>
        </div>
        <div class="a4a">
          <div>
            <img class="icon22" src="../assets/lock.png" alt="">
          </div>
          <div class="a41">
            <input class="input2" :type="passwordType" placeholder="请输入登录密码" v-model="password">
          </div>
          <div class="a42" @click="togglePassword">
          </div>
        </div>
        <div class="a4a">
          <div>
            <img class="icon22" src="../assets/lock.png" alt="">
          </div>
          <div class="a41">
            <input class="input22" :type="passwordType1" placeholder="请确定密码" v-model="password1">
          </div>
          <div class="a42" @click="togglePassword1">
          </div>
        </div>
        <div class="a5">
          <div class="a50">
            <el-checkbox
              v-model="checked"
              checked-color="#3895c5"
              unchecked-color="#dcdcdc"
            ></el-checkbox>
            <div class="a51">记住密码</div>
          </div>
          <div class="a52"></div>
          <div class="a53" @click="log">返回登录</div>
        </div>
        <div class="a6">
          <div class="a622" @click="handleRegister">注册</div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 忘记密码 -->
  <div class="cont" v-if="status === 3">
    <div class="tent">
      <div class="tleft">
        <img class="ti" src="../assets/biao.png" alt="">
      </div>
      <div class="tright">
        <div class="a11">智能配送</div>
        <div class="a22">一款智能AI平台</div>
        <div class="a3a">
          <div>
            <img class="icon11" src="../assets/email.png" alt="">
          </div>
          <div class="a31">
            <input class="input11" type="text" placeholder="请输入邮箱" v-model="emailInputValue">
          </div>
        </div>
        <div class="a3a">
          <div>
            <img class="icon11" src="../assets/verify.png" alt="">
          </div>
          <div class="a31">
            <input class="input1" type="text" placeholder="请输入验证码" v-model="verificationCode">
            <div class="a311">
              <el-button @click="sendCode" class="btn" type="primary" :disabled="isCounting" plain>{{ maxTime }}</el-button>
            </div>
          </div>
        </div>
        <div class="a4a">
          <div>
            <img class="icon22" src="../assets/lock.png" alt="">
          </div>
          <div class="a41">
            <input class="input2" :type="passwordType" placeholder="请输入登录密码" v-model="password">
          </div>
          <div class="a42" @click="togglePassword">
          </div>
        </div>
        <div class="a4a">
          <div>
            <img class="icon22" src="../assets/lock.png" alt="">
          </div>
          <div class="a41">
            <input class="input22" :type="passwordType1" placeholder="请确定密码" v-model="password1">
          </div>
          <div class="a42" @click="togglePassword1">
          </div>
        </div>
        <div class="a5">
          <div class="a50">
            <el-checkbox
              v-model="checked"
              checked-color="#3895c5"
              unchecked-color="#dcdcdc"
            ></el-checkbox>
            <div class="a51">记住密码</div>
          </div>
          <div class="a52"></div>
          <div class="a53" @click="log">返回登录</div>
        </div>
        <div class="a6">
          <div class="a622" @click="confirmReset">确认重置</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref } from 'vue'  // 移除未使用的watch导入
import { ElMessage } from 'element-plus'
import axios from 'axios'

const checked = ref(false)  // 记住密码复选框状态
const status = ref(1)  // 1:登录 2:注册 3:忘记密码
const router = useRouter()
const emailInputValue = ref('')
const password = ref('')  // 存储密码值
const password1 = ref('')  // 存储确认密码值
const showPassword = ref(false)  // 控制密码显示状态
const passwordType = ref('password')  // 控制输入框类型
const showPassword1 = ref(false)
const passwordType1 = ref('password')  // 控制确认密码输入框类型
const maxTime = ref('获取验证码')
const verificationCode = ref('')  // 用户输入的验证码
const isCounting = ref(false)
const countdown = ref(60)
const isEmailRegistered = ref(false)  // 标记邮箱是否已注册
let timer = null

// 初始化：读取本地存储的记住密码
const init = () => {
  const savedUser = sessionStorage.getItem('savedUser')
  if (savedUser) {
    const { email, pwd } = JSON.parse(savedUser)
    emailInputValue.value = email
    password.value = pwd
    checked.value = true
  }
}
init()

// 登录功能
// 登录功能
const login = async () => {
  // 输入验证
  if (!emailInputValue.value) {
    ElMessage.warning('请输入邮箱')
    return
  }
  
  if (!password.value) {
    ElMessage.warning('请输入密码')
    return
  }

  try {
    const response = await axios.post('http://localhost:9000/api/login', 
      {
        email: emailInputValue.value,
        pwd: password.value           
      },
      {
        headers: { 'Content-Type': 'application/json' }
      }
    )
    const data = response.data
    console.log('登录结果', data)

    if (data.code === 200) {
      // 保存SessionID和用户信息到会话存储
      sessionStorage.setItem('sessionId', data.data.sessionId)
      
      // 保存用户基本信息
      sessionStorage.setItem('userInfo', JSON.stringify({
        id: data.data.id,
        email: data.data.email,
        // 如果有其他用户信息如用户名、头像等，也从响应数据中获取
        username: data.data.username || '',
      }))
      
      // 记住密码功能
      if (checked.value) {
        sessionStorage.setItem('savedUser', JSON.stringify({
          email: emailInputValue.value,
          pwd: password.value
        }))
      } else {
        sessionStorage.removeItem('savedUser')
      }
      
      ElMessage.success('登录成功')
      router.push("/HomeViews")
    } else {
      // 错误提示细化
      if (data.msg.includes('不存在')) {
        ElMessage.error('该邮箱未注册，请先注册')
      } else if (data.msg.includes('密码')) {
        ElMessage.error('密码错误，请重新输入')
      } else {
        ElMessage.error(data.msg || '登录失败')
      }
    }
  } catch (error) {
    console.error('登录请求失败', error)
    ElMessage.error('网络错误或服务器异常，请稍后重试')
  }
}

// 跳转到注册页面
const goToRegister = () => {
  status.value = 2
  // 清空表单
  emailInputValue.value = ''
  password.value = ''
  password1.value = ''
  verificationCode.value = ''
}

// 注册功能
const handleRegister = async () => {
  // 验证输入
  if (!emailInputValue.value || !password.value || !verificationCode.value) {
    ElMessage.error('请填写完整信息')
    return
  }
  
  // 邮箱格式验证
  const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailReg.test(emailInputValue.value)) {
    ElMessage.error('请输入有效的邮箱（如xxx@163.com）')
    return
  }
  
  if (password.value !== password1.value) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  try {
    const response = await axios.post('http://localhost:9000/api/register', 
      {
        email: emailInputValue.value,
        pwd: password.value,
        code: verificationCode.value
      },
      {
        headers: { 'Content-Type': 'application/json' }
      }
    )
    const data = response.data
    
    if (data.code === 200) {
      ElMessage.success('注册成功')
      status.value = 1  // 切换到登录界面
      // 清空输入框
      emailInputValue.value = ''
      password.value = ''
      password1.value = ''
      verificationCode.value = ''
    } else {
      ElMessage.error(data.msg || '注册失败')
    }
  } catch (error) {
    console.error('注册请求异常:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 验证码倒计时函数
const startCountdown = () => {
  isCounting.value = true
  maxTime.value = `${countdown.value}s`
  
  timer = setInterval(() => {
    countdown.value--
    maxTime.value = `${countdown.value}s`
    
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCounting.value = false
      maxTime.value = '获取验证码'
      countdown.value = 60  // 重置倒计时
    }
  }, 1000)
}

// 检查邮箱是否已注册并发送验证码
const checkEmailAndSendCode = async () => {
  if (isCounting.value) return

  // 邮箱格式验证
  const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailInputValue.value || !emailReg.test(emailInputValue.value)) {
    ElMessage.error('请输入有效的邮箱（如xxx@163.com）')
    return
  }

  try {
    // 检查邮箱是否已注册
    const checkRes = await axios.post('http://localhost:9000/api/check_email', 
      { email: emailInputValue.value },
      { headers: { 'Content-Type': 'application/json' } }
    )
    
    const checkData = checkRes.data
    
    if (checkData.code === 200 && checkData.isRegistered) {
      isEmailRegistered.value = true
      ElMessage.error('该邮箱已注册，请直接登录')
      return
    }
    
    // 邮箱未注册，发送验证码
    const res = await axios.post('http://localhost:9000/api/send_code', 
      { 
        email: emailInputValue.value,
        scene: 'register'  // 明确指定场景
      },
      { headers: { 'Content-Type': 'application/json' } }
    )
    
    const data = res.data
    if (data.code === 200) {
      ElMessage.success('验证码已发送，请注意查收（可能在垃圾邮件中）')
      // 开始倒计时
      startCountdown()
    } else {
      ElMessage.error(data.msg || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码请求失败', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 忘记密码场景 - 获取验证码
const sendCode = async () => {
  if (isCounting.value) return

  // 邮箱格式验证
  const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailInputValue.value || !emailReg.test(emailInputValue.value)) {
    ElMessage.error('请输入有效的邮箱（如xxx@163.com）')
    return
  }

  try {
    const res = await axios.post('http://localhost:9000/api/send_code', 
      { 
        email: emailInputValue.value,
        scene: 'forgot'  // 明确指定忘记密码场景
      },
      { headers: { 'Content-Type': 'application/json' } }
    )
    
    const data = res.data
    if (data.code === 200) {
      ElMessage.success('验证码已发送，请注意查收')
      startCountdown()
    } else {
      ElMessage.error(data.msg || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码请求失败', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 忘记密码场景 - 确认重置密码
const confirmReset = async () => {
  // 输入验证
  if (!emailInputValue.value) {
    ElMessage.warning('请输入邮箱')
    return
  }
  if (!verificationCode.value) {
    ElMessage.warning('请输入验证码')
    return
  }
  if (!password.value || !password1.value) {
    ElMessage.warning('请输入密码')
    return
  }
  if (password.value !== password1.value) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  try {
    const response = await axios.post('http://localhost:9000/api/reset_password', 
      {
        email: emailInputValue.value,
        pwd: password.value,
        code: verificationCode.value
      },
      { headers: { 'Content-Type': 'application/json' } }
    )
    const data = response.data

    if (data.code === 200) {
      ElMessage.success('密码重置成功，请使用新密码登录')
      status.value = 1; // 重置成功后返回登录界面
      // 清空输入框
      emailInputValue.value = '';
      password.value = '';
      password1.value = '';
      verificationCode.value = '';
    } else {
      ElMessage.error(data.msg || '密码重置失败');
    }
  } catch (error) {
    console.error('密码重置请求失败', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};
// 切换密码显示状态
const togglePassword = () => {
  showPassword.value = !showPassword.value
  passwordType.value = showPassword.value ? 'text' : 'password'
}

const togglePassword1 = () => {
  showPassword1.value = !showPassword1.value
  passwordType1.value = showPassword1.value ? 'text' : 'password'
}

const log = () => {
  status.value = 1
}

const pass = () => {
  status.value = 3
}


</script>
<style>

.cont{
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('../assets/background.png');
  height: 98vh;
  width:99vw ;
}
.tent{
  display: flex;
  background-color: white;
  width: 900px;
  height:500px;
  border-radius: 30px;
  box-shadow: 12px 12px 14px 0px rgba(214, 214, 214, 0.3);
}
.tleft{
  width: 500px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.ti{
  width: 400px;
 
}
.tright{
  flex: 1;
  display: flex;
  
  flex-direction:column
}

.a1{
  font-size: 48px;
  font-weight: 700;
  margin-top: 40px;
}
.a11{
  font-size: 48px;
  font-weight: 700;
  margin-top: 10px;
}
.a2{
  font-size: 15px;
  color: rgb(207, 204, 204);
  margin-bottom: 50px;
}
.a22{
  font-size: 15px;
  color: rgb(207, 204, 204);
  margin-bottom: 20px;
}
.a3{
  display: flex;
  width: 300px;
  height: 40px;
  border: none;                
  border-bottom: 2px solid #e6e4e4; 
  padding-bottom: 10px;
  margin-bottom: 30px; 
  transition: transform 0.2s, border-color 0.3s;      
}
.a3a{
  display: flex;
  width: 300px;
  height: 40px;
  border: none;                
  border-bottom: 2px solid #e6e4e4; 
  padding-bottom: 5px;
  margin-bottom: 20px; 
  transition: transform 0.2s, border-color 0.3s;      
}
.icon1{
  width: 40px;
  
}
.icon11{
  width: 30px;
  margin-top: 5px;
}
.a31{
  display: flex;
  width: 240px;
}
.el-button.btn{
  height: 40px;
  width: 85px;
  margin-left: 10px;
}
.el-button.btn:active{
  transform: scale(0.98);
}
.input1{
  flex: 1;
  border: none;
  outline: none; 
}
.input11{
  flex: 1;
  border: none;
  outline: none; 
}
.a4{
  display: flex;
  width: 300px;
  height: 40px;
  border: none;                
  border-bottom: 2px solid #e6e4e4; 
  padding-bottom: 10px; 
  margin-bottom: 20px; 
  transition: transform 0.2s, border-color 0.3s;      
}

.a4a{
  display: flex;
  width: 300px;
  height: 40px;
  border: none;                
  border-bottom: 2px solid #e6e4e4; 
  margin-bottom: 20px; 
  padding-bottom: 5px; 
  transition: transform 0.2s, border-color 0.3s;      
}
.icon2{
  width: 35px;
  
}
.icon22{
  width: 30px;
  margin-top: 5px;
}

.icon3 {
  width: 20px;
  height: 20px;
}
.a41{
  display: flex;
  width: 240px;
}

.input2{
  flex: 1;
  border: none;
   outline: none; 
}
.input22{
  flex: 1;
  border: none;
  outline: none; 
}
.a3:hover, .a4:hover,.a3a:hover,.a4a:hover {
  transform: translateY(-2px); 
  border-bottom-color: #409eff;  
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); 
}
.a5{
  display: flex;
  width: 300px;
  height: 40px;
  border: none;                
}
.el-checkbox__input .el-checkbox__inner {
  border-color: #3895c5; /*复选框未被选中时*/
  border-width: 1.5px;
}

.a51{
  font-size: 15px;
  color: #828181;
  padding-left: 5px;
  padding-top: 3px;
  transition:transform 0.3s;
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE/Edge */
}
.a50{
  display: flex;
  transition:transform 0.3s;
}
.a50:hover{
  transform: translateY(-1px); 
  border-bottom-color: #409eff;
}
.a53{
  font-size: 15px;
  padding-top: 3px;
  color: #409eff;
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE/Edge */
  cursor: pointer;
  transition:transform 0.2s;
  text-decoration: none;
}

.a53:hover{
  transform: translateY(-1px); 
  border-bottom-color: #409eff;
}
.a53:active{
  transform: scale(0.98) 
  
}
.a52{
  flex:1
}
.a6{
 
  display: flex;
  
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE/Edge */
}

.a61{
  width: 130px;
  height: 50px;
  color: white;
  font-size: 24px;
  border-radius: 30px;
  background-color: cornflowerblue;
  display: flex;
  align-items: center;
  justify-content: center;
  transition:transform 0.2s;
  cursor: pointer;
}

.a62{
  margin-left: 15px;
   width: 130px;
  height: 50px;
  border-radius: 30px;
  background-color: cornflowerblue;
  color: white;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition:transform 0.2s;
  cursor: pointer;
}
.a622{
  margin-left: 15px;
   width: 275px;
  height: 50px;
  border-radius: 30px;
  background-color: cornflowerblue;
  color: white;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition:transform 0.2s;
  cursor: pointer;
}
.a61:hover,.a62:hover,.a622:hover{
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px); 
}
.a61:active,.a62:active,.a622:active{
  transform: scale(0.98);
}
</style>

